package coordinator;

import java.io.File;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Arrays;
import java.util.List;
import java.util.Map; 
import java.util.Set;

import org.apache.log4j.Logger;

import discovery.DiscoveryCoordinator;

import registry.DiscoveryRegistry;
import rmi.RmiStarter;
import testnode.ITestNode;
import testnode.TestNode;
import utility.ConfigManager;

public class CoordinatorStarter extends RmiStarter {
	
	Registry registry;
	ConfigManager config;
	Logger logger = Logger.getLogger(this.getClass());

	public CoordinatorStarter()
	{
		super();
	}
	
	@Override
	public void doCustomRmiHandling() {
		try{
			config = ConfigManager.getInstance();
			int port = config.getInt("registryPort");
			registry = LocateRegistry.getRegistry(port);
		}
		catch(Exception e)
		{
			logger.error("Config error", e);
		}
	}
	
	public void runTest() {
		try {
			DiscoveryCoordinator disco = new DiscoveryCoordinator();
			
			if(config == null)
				 config = ConfigManager.getInstance();
			
			String srcDir = config.getString("srcDir");
			String installDir = config.getString("installDir");
							
			List<String> preconfiguredNodes = Arrays.asList(config.getStringArray("testNodeAddress"));

			Map<String, String> setOfClients = null;
			if (preconfiguredNodes.isEmpty()) {
				setOfClients = disco.getAvailableNodes();
			}
			else {
				setOfClients = disco.getAvailableNodes(preconfiguredNodes);
			}		
			
			Set<String> setOfClientNames = setOfClients.keySet();
			logger.debug("Found " + setOfClientNames.size() + " clients.");
			for(String clientName: setOfClientNames) {
				try
				{
					ITestNode testNode = (ITestNode)registry.lookup(clientName);
					
					Coordinator coordinator = new Coordinator();
					
					File sourceFile = new File(srcDir+"/HelloWorld.class");
					
					coordinator.InstallOnTestNode(testNode, sourceFile);
		
					logger.debug("installed on "+clientName+": "+"HelloWorld.class");
		
					String[] args = {installDir};
					 
					coordinator.executeOnTestNode(testNode, "test.HelloWorld", args);
		
					logger.debug("executed on "+clientName+": "+"HelloWorld.class");
				}
				catch(Exception ex)
				{
					logger.error("Fehler bei Installation / Ausführung von TestNode "+ clientName, ex);
				}
			}

		} catch (Exception e) {
			logger.error("Fehler beim Sammeln der Nodes:", e);
			
		}
	}
	
	public static void main(String[] args) {
		new CoordinatorStarter().runTest();
	}

}
